package main

import (
	"fmt"
	"net"
	"strings"
)

type User struct {
	Name    string
	Ip      string
	Channel chan string
	conn    net.Conn
	server  *Server
}

// 创建一个用户
func CreateUser(conn net.Conn, server *Server) *User {
	ip := conn.RemoteAddr().String()
	user := &User{
		Name:    ip,
		Ip:      ip,
		Channel: make(chan string),
		conn:    conn,
		server:  server,
	}

	//启动goroutine监听消息
	go user.ListenMessage()
	return user
}

func (this *User) ListenMessage() {
	for {
		//从channel中读取数据
		msg := <-this.Channel
		//写到客户端
		this.conn.Write([]byte(msg + "\n"))
	}
}

func (this *User) Online() {
	this.server.mapLock.Lock()
	this.server.OnlineMap[this.Name] = this
	this.server.mapLock.Unlock()
	//广播当前用户上线消息
	this.server.BroadCast(this, "已上线")
}

func (this *User) Offline() {
	this.server.mapLock.Lock()
	delete(this.server.OnlineMap, this.Name)
	this.server.mapLock.Unlock()
	this.server.BroadCast(this, "已下线")
}

func (this *User) SendMsg(msg string) {
	this.conn.Write([]byte(msg))
}

func (this *User) DoMessage(msg string) {
	if msg == "who" {
		//查询当前用户
		this.server.mapLock.Lock()
		for _, user := range this.server.OnlineMap {
			onlineMsg := "[" + user.Ip + "]" + user.Name + ":" + "在线..."
			this.SendMsg(onlineMsg)
		}
		this.server.mapLock.Unlock()
	} else if len(msg) > 7 && msg[:7] == "rename|" {
		newName := strings.Split(msg, "|")[1]
		_, user := this.server.OnlineMap[newName]
		if user {
			this.SendMsg("当前用户名已被使用\n")
		} else {
			this.server.mapLock.Lock()
			delete(this.server.OnlineMap, this.Name)
			this.server.OnlineMap[newName] = this
			this.server.mapLock.Unlock()
			this.Name = newName
			this.SendMsg("您已更新用户名：" + this.Name + "\n")
		}

	} else if len(msg) > 4 && msg[:3] == "to|" {
		//消息格式： to|张三|消息内容

		//1、获取对方用户名
		remoteUsername := strings.Split(msg, "|")[1]
		if remoteUsername == "" {
			this.SendMsg("消息格式不正确")
			return
		}

		//2、根据用户名获取User对象
		remoteUser, ok := this.server.OnlineMap[remoteUsername]
		if !ok {
			this.SendMsg("用户不存在")
			return
		}

		//3、获取消息内容发给对方客户端
		content := strings.Split(msg, "|")[2]
		if content == "" {
			this.SendMsg("消息内容不能为空")
			return
		}
		remoteUser.SendMsg(fmt.Sprintf("from|%s|%s", this.Name, content))
	} else if len(msg) > 7 && msg[:7] == "public|" {
		content := strings.Split(msg, "|")[1]
		this.server.BroadCast(this, content)
	}

}
